package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.*;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 安全文明施工措施费用评审
 * Created by glodon on 2019-09-27.
 */
public class SafeConstructionNewJob implements StepJobJdbcFactory {
    private JdbcTemplateService jdbcTemplateService;
    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode,String expertId,String layouCode)
            throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
        paramMap.put("submitCode", submitCode);
        paramMap.put("sectionId", beSectionStepJob.getSectionId());
        //获取安全文明施工费分析明细
        List<Map<String, Object>> list  = jdbcTemplateService.selectForList("select ProjectID,BidID,ManageNodeID,IdxCode,Code,ManageNodeName,CostBase,CostRate,spectype,round(CostBase*CostRate/100,2) as underCost from" +
                " (select a.mano_projectid as ProjectID, a.enterprise_id as BidID, a.mano_managenodeid as ManageNodeID,\n" +
                "         a.mano_idxcode as IdxCode, a.mano_code as Code, CONCAT(b.mano_name,'-',a.mano_name) as ManageNodeName,\n" +
                "         ifnull(vi_b.RGFTotal,0)+ifnull(vi_m.RGFTotal,0)+ifnull(vi_b.JXFTotal,0)+ifnull(vi_m.JXFTotal,0) as CostBase,\n" +
                "        c.cora_HJBHUnder as CostRate, a.mano_spectype as spectype\n" +
                "          from td_ManageNode_Bid a\n" +
                "           left join be_section_info d on a.mano_projectid = d.td_projectId\n" +
                "          left join td_ManageNode as b on a.mano_projectid=b.mano_projectid\n" +
                "                and a.mano_parentid=b.mano_managenodeid and b.mano_projectid=d.td_projectId\n" +
                "          inner join td_CostRate c on a.mano_projectid=c.cora_ProjectID\n" +
                "                and c.cora_ManageNodeID=a.mano_ManageNodeID and c.cora_ProjectID=d.td_projectId\n" +
                "          left join vi_budgetnodecost vi_b on vi_b.ProjectID=a.mano_ProjectID\n" +
                "            and vi_b.BidID=a.enterprise_id and vi_b.ManageNodeID=a.mano_ManageNodeID\n" +
                "            and vi_b.ProjectID=d.td_projectId\n" +
                "          left join vi_measuresnodecost vi_m on vi_m.ProjectID=a.mano_ProjectID\n" +
                "            and vi_m.BidID=a.enterprise_id and vi_m.ManageNodeID=a.mano_ManageNodeID\n" +
                "            and vi_m.ProjectID=d.td_projectId\n" +
                "            where d.seq_id=:sectionId and a.mano_Type=2\n" +
                "            order by a.enterprise_id,IdxCode) a", paramMap);
        //获取单位列表
        List<Map<String, Object>> enterList = jdbcTemplateService.selectForList("select a.seq_id enterpriseId, b.biin_name enterpriseName,b1.total \n" +
                "                from be_section_enterprise a join td_bidinfo b on a.seq_id = b.enterprise_id \n" +
                "left join (select meno_projectid, enterprise_id, sum(ifnull(meno_Total, 0)) as total\n" +
                "                 from td_MeasuresNode_Bid where meno_Type = '11' and meno_ManageNodeID=\n" +
                "                 '00000000-0000-0000-0000-000000000000' group by meno_projectid, enterprise_id) b1 \n" +
                "        on b.enterprise_id = b1.enterprise_id and a.bid_projectid=b1.meno_projectid\n" +
                "                where a.section_id = :sectionId", paramMap);
        //获企业管理费单位列表
        for(Map<String, Object> map : enterList){
            Double tjRate = 0.0;
            Double tjBase = 0.0;
            int tjCount = 0;
            Double underCostTotal = 0.0;
            for(Map<String, Object> detailMap : list) {
                if(OConvertUtils.getString(map.get("enterpriseId")).equals(OConvertUtils.getString(detailMap.get("BidId")))){
                    //各单位工程取费基数
                    Double costBase = OConvertUtils.getDouble(detailMap.get("CostBase"),0.0);
                    //各单位工程费率
                    Double costRate = OConvertUtils.getDouble(detailMap.get("CostRate"),0.0);
                    //土建专业
                    if (OConvertUtils.getInt(detailMap.get("spectype")) == 1){
                        //存储费率(因为所有的土建专业费率必须一致，所以只要记录一个即可)
                        tjRate = costRate;
                        //汇总非土建专业的报价
                        tjBase += costBase;
                        tjCount++;
                    } else {
                        //汇总非土建专业的报价
                        underCostTotal += OConvertUtils.getDouble(detailMap.get("underCost"),0.0);;
                    }
                }
            }
            if(tjCount > 0) {
                //最低报价汇总土建专业报价
                underCostTotal += calculateTjCost(tjBase, tjRate);
            }
            map.put("underCostTotal", underCostTotal);
        }

        //保存计算结果
        saveResult(beSectionStepJob.getSectionId(), beSectionStepJob.getSectionStepId(), enterList);
        return true;
    }

    /**
     * 计算汇总土建专业最低报价
     * @param tjBase 土建基数
     * @param tjRate 土建费率
     * @return
     */
    private Double calculateTjCost(Double tjBase, Double tjRate){
        Double result;
        if(tjBase < 5000000) {
            //取费基数额度500万元已内的执行标准费率
            result = tjBase * tjRate/100;
        } else if (tjBase < 20000000) {
            //500万元以上至2000万按标准费率乘0.9
            result = 5000000 * tjRate/100;
            result += (tjBase - 5000000) * tjRate/100 * 0.9;
        } else if (tjBase < 50000000) {
            //2000万以上至5000万按标准费率乘0.8
            result = 5000000 * tjRate/100;
            result += (20000000 - 5000000) * tjRate/100 * 0.9;
            result += (tjBase - 20000000) * tjRate/100 * 0.8;
        } else {
            //5000万元以上按标准费率乘0.7
            result = 5000000 * tjRate/100;
            result += (20000000 - 5000000) * tjRate/100 * 0.9;
            result += (50000000 - 20000000) * tjRate/100 * 0.8;
            result += (tjBase - 50000000) * tjRate/100 * 0.7;
        }
        return result;
    }

    /**
     * 保存计算结果
     * @param sectionId 标段id
     * @param sectionStepId 环节id
     * @param enterList 企业计算结果
     * @throws Exception
     */
    private void saveResult(String sectionId, String sectionStepId,List<Map<String, Object>> enterList) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sectionStepId", sectionStepId);
        paramMap.put("sectionId", sectionId);
        List<BeComputerResult> beComputerResultList = new ArrayList<>();
        BeComputerResult beComputerResult = null;
        for(Map<String, Object> map: enterList) {
            beComputerResult = new BeComputerResult();
            beComputerResult.setSeqId(IdsUtil.uuid());
            beComputerResult.setSectionId(sectionId);
            beComputerResult.setC1(OConvertUtils.getString(map.get("underCostTotal")));
            beComputerResult.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
            beComputerResult.setSectionStepId(sectionStepId);
            beComputerResult.setCreateTime(DateUtil.now());
            //报出金额小于最低金额,则不通过
            if(OConvertUtils.getDouble(map.get("total"), 0.0) < OConvertUtils.getDouble(map.get("underCostTotal"), 0.0)){
                beComputerResult.setIsPassed("0");
            } else {
                beComputerResult.setIsPassed("1");
            }
            beComputerResultList.add(beComputerResult);
        }
        //删除已存在的结果，防止重复存入
        jdbcTemplateService.update(" DELETE FROM be_computer_result WHERE section_step_id=:sectionStepId and section_id=:sectionId", paramMap);
        //批量转数组,插入数据
        SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(beComputerResultList);
        jdbcTemplateService.bathInsert("insert into be_computer_result (seq_id, section_step_id, section_id,enterprise_id, c1,create_time,is_passed)\n" +
                "    values(:seqId, :sectionStepId, :sectionId,:enterpriseId,:c1,:createTime,:isPassed)",beanSources);
    }
}
